package com.topdt.jbpm.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringEscapeUtils;

import com.thx.common.util.AppContext;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMakerUtils {
	private static final Configuration configuration = new Configuration();

	public static Template getTemplate(String name,String directory) throws IOException {
		configuration.setObjectWrapper(new DefaultObjectWrapper());
		configuration.setDirectoryForTemplateLoading(new File(directory));
		configuration.setEncoding(Locale.CHINA, "UTF-8");
		Template template = configuration.getTemplate(name);
		return template;
	}
	
	public static Template getTemplateByForm(byte[] templetByte) throws IOException {
		configuration.setObjectWrapper(new DefaultObjectWrapper());
		configuration.setEncoding(Locale.CHINA, "UTF-8");
		configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
		Reader reader = new InputStreamReader(new ByteArrayInputStream(templetByte),"utf-8");
		Template template = new Template(null, reader, configuration);
		return template;
	}


	/**
	 *  @Description    : Jsoup在把带有freemarker语法标记的html转化
	 *  					的时候进行了转义，导致freemarker标记被错误的
	 *  					解析了，需要把误解析的标记替换成正常的标记。
	 *  					例如:"</#if>"被Jsoup解析的时候会变成"<!--#if-->"
	 *  					，需要替换回来。
	 *  @param htmlSource	带有freemarker标记被误解析以后的html字符串
	 *  @return
	 *  @return         : String 正常freemarker标记语法的html字符串
	 *  @version        : v1.00
	 */
	public static String unescapeFreemarkerToHtmlForJsoup(String htmlSource) {
	  
	    htmlSource = StringEscapeUtils.unescapeHtml4(htmlSource);
		Pattern p = Pattern.compile("<!--#\\w+-->");
		Pattern p1 = Pattern.compile("\\w+");
		Matcher m = p.matcher(htmlSource);
		StringBuffer sb = new StringBuffer();
		while(m.find()) {
			String str = m.group();
			Matcher m1 = p1.matcher(str);
			if(m1.find()) {
				m.appendReplacement(sb, "</#"+m1.group()+">");
			}
		}
		m.appendTail(sb);
		return sb.toString();
	}
}
